//PacMan Console Game
//Heritage University CPSC 240

//Includes
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <time.h>
#include <process.h>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
//End of includes

enum direction {Up, Down, Left, Right, None};

/*------------------------------Function Prototypes---------------------------*/
// I have chaged the ghost function by adding a new variable which I used to slow down the ghost
void boostColor(char grabbedChar, int amountAllowed, bool boostOn);

//Resizes game console to game grid size
void consoleResize(unsigned int x, unsigned int y);
void setColorOnGrid(char grabbedChar,int amountAllowed);
void toQuitTheGame(bool &toRun);
void clearBuffer(char &movingDirection); // this function's purpose is to clear out useless user input
void consoleResize(unsigned int x, unsigned int y);
void clearScreen();
void sound(void *);
void Game(bool &reset);
void setcolor(unsigned short color);
void HighScores(void);
void Bubblesort(void);
void GameMenu(bool &exitGame);//Tyler-Start Menu
int getOption();//Tyler-Start Menu Options
void ghostDeath(int &ghostExterminator, int &ghostTimeOff);//Israel
void youAreSoDead(bool Death);//Israel
void clickTime(int &time,int &Loop);//Israel
void lifeDecrementation(int &numberOfLives, bool Death);//Israel
void displayOfTheLivesPacmanHasLeft(int numberOfLives);//Israel
direction keyToDirection(char key);

//This function moves the ghost randomly--Edgar
void ghostDudeRandom(int &amountAllowed,int &ghostPosY, int &ghostPosX, 
    int pacManPosY, int pacManPosX, char grid[17][17],
    int pathReplaceY, int pathReplaceX,char ghost); 
// Trino's ghost function
void ghostDudeChasing(int &ghostPosY, int &ghostPosX, int pacManPosY,
	int pacManPosX, char grid[17][17]); // This function is for the ghost to chase pacman


/***************************************Begin Main***************************/
int main(){
    //Variables & Constants
    bool exitGame = false;
    
    //Resize the console to game fit game grid
    consoleResize(50,50);
    
    //Begin the background sound thread.
    _beginthread(sound, 0, NULL);
    
    //Call the game's meuning system   
    do {             
       GameMenu(exitGame);
    }while(exitGame != true);

return 0;}
/*************************************End of Main is *************************/


// This is the games primary menu.  All aspects of the game are controlled 
//via the menu
void GameMenu(bool &exitGame){
     
     //Function Variables
     int number_Entered = 0;
     bool reset = true;
     
      do{
           //Otain user's menu selection
           number_Entered = getOption();

           /*Perform switch-statement to select the number 
           the user has called upon*/    
           switch(number_Entered)
           {
              case 1:
                  //Play Game            
                  cout << "PLAY GAME" << endl;     
                  //Call function to play game
                  Game(reset);
                  break;
              case 2:
                  //Exit Program
                  cout << "EXIT GAME " << endl;
                  exitGame = true;
                  break;
              default:
                  //Display to user that they have entered an invalid option
                  cout << "Invalid menu option; please try again.";
                  break;
              }}//End of switch statement & do statement
      while(number_Entered != 2); //End of do-while loop    
                 

           //For Dev Compiler-Remove for other
           system ("PAUSE");
           
           //Clear screen
           clearScreen();
//End of function     
}

direction keyToDirection(char key){
	switch(key)
	{
		case 'H':
			return Up;
			break;
		case 'P':
			return Down;
			break;
		case 'K':
			return Left;
			break;
		case 'M':
			return Right;
			break;
		default:
			return None;
		return None;
	}
}

bool isValidMove(char grid[17][17], int y, int x, direction thisDirection){
	const char wall = 219;
	int x_move, y_move;
	switch(thisDirection)
	{
		case Up:
			x_move = x-1;
			y_move = y;
			break;
		case Down:
			x_move = x+1;
			y_move = y;
			break;
		case Left:
			x_move = x;
			y_move = y-1;
			break;
		case Right:
			x_move = x;
			y_move = y+1;
			break;
		case None:
			return true;	// should be valid to move nowhere...
	}
	if (grid[y_move][x_move]!=wall) {
		return true;
	} else {	
		return false;
	}
	return true;
}

//Game Function
void Game(bool &reset){
    int score = 0;  
    //Game grid character constants
    const char boost = 15, wall = 219, path = 249, escape = 27, packDude = 2;
    char ghost = 1;
    bool run = true;
    //Define Pacman's position on the playing board
    int pacManPosY = 6, pacManPosX = 8;
    int pathReplaceY = 0;
    int pathReplaceX = 0;
    int ghostPosY = 15;
    int ghostPosX = 14;
    int m = 0;
    
	char characterForColorCheck = ' ';
    char emptyPath = ' ';
    char currentGridItem;
    char posForBoost;
    char whereToMove = ' ';
    time_t seconds();
    bool boostOn = false;
    bool coolColors = false;
    
    vector<char> Vector;
    char crystal = 3;
    
    int CountDownTimeForGhostKilling = 18;// This is the ghost countdown timer they have to escape from pacman.
    int clockTicker =20;
    int loopRepeats = 0;//This is needed to keep the timer running!
    int clik = 0;//This is just a counter that keeps track on the first time the ghost moves!
    int iLive = 3;
    bool dieYesOrNo = true;
	
	direction requestedDirection;
	bool validMove;
    
ifstream ipnt_logo("Logo2.txt");    
//========================================================================begins    
    
    int amountAllowed = 0; // This variable is used to control the speed of the ghost

//==========================================================================ends 
    char grid[17][17] = {
 /*        0    1    2    3    4    5    6    7    8    9   10   11   12   13  14    15   16 */
 /*0*/   {wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall},
 /*1*/   {wall,boost,path,path,path,path,path,path,boost,path,path,path,path,path,path,boost,wall},
 /*2*/   {wall,path,wall,wall,path,wall,wall,wall,path,wall,wall,wall,path,wall,wall,path,wall},
 /*3*/   {wall,path,path,path,path,path,path,wall,path,path,path,path,path,path,wall,path,wall},
 /*4*/   {emptyPath,path,wall,path,wall,wall,path,path,path,wall,crystal,wall,wall,path,path,path,emptyPath},
 /*5*/   {wall,path,path,path,wall,wall,path,wall,path,wall,wall,wall,wall,path,wall,path,wall},
 /*6*/   {wall,path,wall,path,path,path,path,path,packDude,path,path,path,path,path,wall,path,wall},
 /*7*/   {wall,path,wall,wall,wall,path,wall,wall,wall,wall,wall,path,wall,wall,wall,path,wall},
 /*8*/   {wall,path,path,boost,path,path,path,path,path,path,path,path,path,boost,path,path,wall},
 /*9*/   {wall,path,wall,wall,wall,path,wall,wall,wall,wall,wall,path,wall,wall,wall,path,wall},
 /*10*/  {wall,path,path,wall,path,path,path,path,wall,path,path,path,wall,path,path,path,wall},
 /*11*/  {wall,path,path,path,path,wall,wall,path,path,path,wall,path,wall,path,wall,path,wall},
 /*12*/  {emptyPath,path,wall,wall,path,wall,wall,wall,path,wall,wall,path,path,path,path,path,emptyPath},
 /*13*/  {wall,path,wall,path,path,path,path,path,path,path,path,path,wall,wall,wall,path,wall},
 /*14*/  {wall,path,wall,path,wall,wall,wall,path,wall,wall,wall,path,wall,wall,wall,path,wall},
 /*15*/  {wall,boost,path,path,path,path,path,path,boost,path,path,path,path,path,ghost,boost,wall},
 /*16*/  {wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall},
};
   

    while(run == true) {
                if(time(0)){
   m++;
    }
        cout << "PacDude Ultra 3" << endl;    
    
        //Perform for loop to output grid to console

        for(int row = 0; row < 17; row++) {

            for(int col = 0; col < 17; col++) {
//=========================================================================begins		
                amountAllowed++; 
                /* Like I said this changes the speed of the ghost and I did not want to put it in 
                the ghost function becasue everytime it was reset to zero and 
                returning it as a value by using the ghost fucntion was not the way I wanted to used it.
                So I utilized it as a pointer. This value is very important so pay attention to it in my code.
                */
//==========================================================================ends		
				/**** If there is user Input, this 'if' loop will run ****/
                if(kbhit()) {
        
                whereToMove = getch();
				requestedDirection = keyToDirection(whereToMove);
				validMove = isValidMove(grid, pacManPosY, pacManPosX, requestedDirection);
				

					// This loop will control packDude's movement to the top
                    if((whereToMove == 'H')&&((grid[pacManPosY-1][pacManPosX] !=wall)
                      ||(grid[pacManPosY-1][pacManPosX]==emptyPath))) {
                    
                        currentGridItem = grid[pacManPosY][pacManPosX];
                        
                        // Will make adjustments for the path and pacman
                        pathReplaceY = pacManPosY-1;
                        pathReplaceX = pacManPosX;
                        
                        // Will change the values
                        grid[pacManPosY][pacManPosX] = emptyPath;
                        pacManPosY--;
                        
						// Will calculate the score for every pellet that the pacman eats
                        if(grid[pathReplaceY][pathReplaceX] == path) {
							score++;
                        }
						// For every boost eaten, 50 points will be added
						else if(grid[pathReplaceY][pathReplaceX] == boost) {
							score = score + 50;
							posForBoost = grid[pathReplaceY][pathReplaceX];
                      m = 0;
                       boostOn = true;
							
						}
                        
                        grid[pathReplaceY][pathReplaceX] = currentGridItem;
                    }
					
					// This loop will control packDude's movement downward
                    else if((whereToMove == 'P')&&((grid[pacManPosY+1][pacManPosX] !=wall)
                           ||(grid[pacManPosY+1][pacManPosX]==emptyPath))){
                       
                        currentGridItem = grid[pacManPosY][pacManPosX];

                        pathReplaceY = pacManPosY+1;
                        pathReplaceX = pacManPosX;                     

                        grid[pacManPosY][pacManPosX] = emptyPath;
                        pacManPosY++;
                        
						// Will calculate the score for every pellet that the pacman eats
                        if(grid[pathReplaceY][pathReplaceX] == path){
							score++;
                        }
						// For every boost eaten, 50 points will be added
						 if(grid[pathReplaceY][pathReplaceX] == boost){
							score = score + 50;
							posForBoost = grid[pathReplaceY][pathReplaceX];
                      m = 0;
                       boostOn = true;
						}
                        
                        grid[pathReplaceY][pathReplaceX] = currentGridItem;
                        
                    }
					
					// This loop will control packDude's movement to the left
                    else if((whereToMove == 'K')&&((grid[pacManPosY][pacManPosX-1] !=wall)
                           ||(grid[pacManPosY][pacManPosX-1]==emptyPath) )){
                    
                        currentGridItem = grid[pacManPosY][pacManPosX];
                        
                        pathReplaceY = pacManPosY;
                        pathReplaceX = pacManPosX-1;                     

                        grid[pacManPosY][pacManPosX] = emptyPath;
                        pacManPosX--;
                        
						// Will calculate the score for every pellet that the pacman eats
                        if(grid[pathReplaceY][pathReplaceX] == path){
							score++;
                        }
						// For every boost eaten, 50 points will be added
						else if(grid[pathReplaceY][pathReplaceX] == boost){
							score = score + 50;
						posForBoost = grid[pathReplaceY][pathReplaceX];
                       m = 0;
                       boostOn = true;

						}
                        
                        grid[pathReplaceY][pathReplaceX] = currentGridItem;
                        
						// for "warp" to other side of screen via empty path
                        if(pacManPosY == 4 && pacManPosX == 0){
                        grid[4][16] = currentGridItem;
                        pacManPosY = 4;
                        pacManPosX = 16;
                        grid[pathReplaceY][pathReplaceX] = emptyPath;
                        }
                        
                        if(pacManPosY == 12 && pacManPosX == 0){
                        grid[12][16] = currentGridItem;
                        pacManPosY = 12;
                        pacManPosX = 16;
                        grid[pathReplaceY][pathReplaceX] = emptyPath;
                        }
}


					// This loop will control packDude's movement to the right
                    else if((whereToMove == 'M')&&((grid[pacManPosY][pacManPosX+1]!= wall)
                           ||(grid[pacManPosY][pacManPosX+1]==emptyPath) )){
						
                        currentGridItem = grid[pacManPosY][pacManPosX];
                        
                        pathReplaceY = pacManPosY;
                        pathReplaceX = pacManPosX+1;                     

                        grid[pacManPosY][pacManPosX] = emptyPath;
                       
						// Will calculate the score for every pellet that the pacman eats
                        if(grid[pathReplaceY][pathReplaceX] == path){
							score++;
                        }
						// For every boost eaten, 50 points will be added
						if(grid[pathReplaceY][pathReplaceX] == boost){
							score = score + 50;
						posForBoost = grid[pathReplaceY][pathReplaceX];
						               m = 0;
						               boostOn = true;
						}
                        grid[pathReplaceY][pathReplaceX] = currentGridItem;
                             pacManPosX++;
						                    
						// for "warp" to other side of screen via empty path
						if(pacManPosY == 4 && pacManPosX == 16){
	                        grid[4][0] = currentGridItem;
	                        pacManPosY = 4;
	                        pacManPosX = 0;
	                        grid[pathReplaceY][pathReplaceX] = emptyPath;
                        } else if(pacManPosY == 12 && pacManPosX == 16){
	                        grid[12][0] = currentGridItem;
	                        pacManPosY = 12;
	                        pacManPosX = 0;
	                        grid[pathReplaceY][pathReplaceX] = emptyPath;
                        }
                    }
					// This statement will end the whole loop if the user presses ESC
                    else if(whereToMove == escape){
						toQuitTheGame(run);
                    }

                    /* Trinidad Estrada:
                       This else loop will attempt to clear out the buffer if there is
                       no Input made by the user. */
                    else{
                        
                        // This function will grab the character determining the user's
                        // move
                        clearBuffer(whereToMove);
                    }
                }
                /****The use Input loop will end here****/

                
                
				// Whatever character is stored in the array,will get stored to 
                // 'characterForColorCheck'
				characterForColorCheck = grid[row][col];
				
				// This function will make the color changes on the grid
                setColorOnGrid(characterForColorCheck,amountAllowed);
                  
                  
                       
                 //  BoostOn needs to be reset to true in this function in order to get colors for other pellets                                               
				/*
                if(boostOn == true){
                  
                    boostColor(characterForColorCheck,amountAllowed,boostOn);              
                    
                }
				if(m == 18){
					boostOn = false;
					ghost = 1;
				} 
				*/

							
	if(grid[pathReplaceY][pathReplaceX] == boost){
							score = score + 50;
                        }
                cout << grid[row][col];
                
                        
            }

        cout << endl;
        }

        setcolor(15);
        //clickTime(clockTicker,loopRepeats);//This is the timer's Prototype
        //youAreSoDead(dieYesOrNo);//This is the gameover prototype that will initialize whether the game should be reset.

        displayOfTheLivesPacmanHasLeft(iLive);
        cout << endl << "PacMan Pos: " << pacManPosY << " " << pacManPosX;
        cout << endl << "Ghost Pos: " << ghostPosY << " " << ghostPosX;
        cout << endl << "Score " << score; // Will display the score's value, 
		cout << endl << "Direction: " << requestedDirection;
        cout << endl << "Time is: " << clockTicker;

        loopRepeats++;//FYI this 'loopRepeats' is needed to keep the timer running!
        
        //This conditional is here to prevent the ghost's timer to display the first time,
        // that way it doesn't confuse the user.
		/*
        if((m==0)||(clik>0)){
        ghostDeath(CountDownTimeForGhostKilling, m);//This will display the time to the user
                                                    // on how much time the ghost will have before pac-man dies.
         clik++;}
		 */
         //If you need to see the time of the ghosts you can block my function, and
         // use the cout statement you had before cout << endl << m; //It works fine!
         
        //cout << endl << exitGame;
//========================================================================begins				
        
		// Trino E.: 
		// This is the ghost function, which will call the ghost(s).
		// For now, the ghost is suppose to chase pacman. Edgar is working on the random ghost movement.
		// When Edgar has done finishing his ghost part, a conditional statement will need to be implemented,
		// that way the game can know when the ghost should be chasing pacman, and when it shouldn't. 
		
		/*
		ghostDudeChasing(ghostPosY, ghostPosX, pacManPosY, pacManPosX, grid);		
				
				//I don't know what exactly is this
                if(grid[pathReplaceY][pathReplaceX] == ghost || grid[pathReplaceY][pathReplaceX] == ' ' || grid[pathReplaceY][pathReplaceX] == path){
                    grid[pathReplaceY][pathReplaceX] = packDude;   
                }
         
                if(grid[ghostPosY][ghostPosX] == packDude || grid[ghostPosY][ghostPosX] == ' ' || grid[ghostPosY][ghostPosX] == path){
                    grid[pathReplaceY][pathReplaceX] = ghost;   
                }  
                if(grid[ghostPosY][ghostPosX] == grid[pathReplaceY][pathReplaceX] && boostOn == true){
                    run = true;
					ghost = 29;
                    grid[pathReplaceY][pathReplaceX] = packDude;
                    grid[ghostPosY][ghostPosX] = ghost;
                }                  
                else if(grid[ghostPosY][ghostPosX] == grid[pathReplaceY][pathReplaceX] && boostOn == false){
					run = false;
                    Beep(290,99);Beep(290,99);Beep(290,99);Beep(290,99);Beep(290,99);
                }
		*/
 
//==========================================================================ends                    	
              
		// 
        Sleep(150);
        system("CLS");
    }

    setColorOnGrid(characterForColorCheck,amountAllowed); 
    
consoleResize(200,200);
coolColors = true;

/*ipnt_logo >> noskipws;  
    while(ipnt_logo >> logo){

    Vector.push_back(logo);
    b++;

}*/


/*
while(b != 0){
   cout << noskipws << Vector[c++];
   b--;
}
cout << "                                                                                                  GAME OVER" << endl; 
system("pause");
system("CLS");

cout << "Do YoU WiSh To TrY AgAiN? y/n ";

string game;

cin >> game ;
if(game == "y"){
        reset = true;
}
else if(game == "n"){
     reset == false; 
}*/
}



// This function will allow color to be displayed on the console window
void setcolor(unsigned short color){                //The function that you'll use to
                                                    //set the colour
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hcon,color);
}

//========================================================================begins

// This function will take charge of the ghost's movement
void ghostDudeRandom(int &amountAllowed,int &ghostPosY, int &ghostPosX, 
               int pacManPosY, int pacManPosX, char grid[17][17], 
               int pathReplaceY, int pathReplaceX,char ghost){

    char wall = 219;
    //char path = 249;
    char tempTwo = ' ';
    //char pacDude = 2;
    //char emptyPath = ' ';
    
//''New Variables''''New Variables''''New Variables''''New Variables''''New Variables'' 
    
    bool tempRightEnabled = true;  // Enables the ghost to move right
    bool tempLeftEnabled = false;  // Enables the ghost to move Left
    bool tempDownEnabled = true;   // Enables the ghost to move down
    bool tempUpEnabled = false;    // Enables the ghost to move up
    int x = 0;                     // Controls the amount of looping
    //int time = 0;                  // It is for the timer (not in use)
    char temp1 = ' ';              // It is for the position checker (not really in use)
    char temp2 = ' ';              // It is for the position checker (not really in use)
    
//''New Variables''''New Variables''''New Variables''''New Variables''''New Variables''   

    pathReplaceY = ghostPosY;
    pathReplaceX = ghostPosX;
    temp1 = ghostPosY;
    temp2 = ghostPosX;

//**Critical****Critical****Critical****Critical****Critical****Critical****Critical*     
    /* This is the equalizer I was talking about
       to move the rate at witch the ghost moves, all you have to do is 
       move the divisor up or down and the rate will change. However I think 
       there is another factor taking place. That factor I think is how much looping should 
       be done after the equalier test.
    */
       
    
    if (amountAllowed%100 == 0) {
        tempRightEnabled = false;
    }
    if (amountAllowed%170 == 0) {
        tempLeftEnabled = true;
    }
    if (amountAllowed%170 == 0) {
        tempUpEnabled = true;
    }
    if (amountAllowed%130 == 0) {
        tempDownEnabled = false;
    }
//**Critical****Critical****Critical****Critical****Critical****Critical****Critical*
    
    // This is a timer I am trying to build into the ghost!
    /*time = time(0);
    if (time % 20 == 0){
        downRight = -4;
    }
    if (time % 40 == 0){
        downRigt = 0;
    }*/

/* The conditionals set here work with the equalizer and the same idea is behind each direction of movement  
  
  What happenes here is that the equalizer tells the conditionals whether or not the gohst can move
  in that direction or not and the amount of movement that can be done.
  You can control the rate by also adding another incrementation of x. However be careful because 
  each thing you do may affect the ghost's movement in a way you wouldn't want it to.
  
  I have adjusted the ghost's movements some what and I think his 
  movement is now going to be a matter of just adjusting them.

*/
    if(tempUpEnabled == false && grid[ghostPosY-1][ghostPosX] != wall){
         while(x != 1 && grid[ghostPosY-1][ghostPosX] != wall){
             pathReplaceY = pathReplaceY-1;
             tempTwo = grid[pathReplaceY][pathReplaceX];
             grid[pathReplaceY][pathReplaceX] = ghost;
             grid[ghostPosY][ghostPosX] = tempTwo;
             ghostPosY--;
             x++;
         } 
     }       
     
     // This is a timer I am trying to build into the ghost!        
     /*  
     if (time % 20 == 0){
         upLeft = 4;
     }
     if (time % 40 == 0){
         upLeft = 0;
     } */ 
        
         
      else if(tempDownEnabled == true && grid[ghostPosY+1][ghostPosX] != wall){
             while(x != 2 && grid[ghostPosY+1][ghostPosX] != wall){
                 pathReplaceY = pathReplaceY+1;
                 tempTwo = grid[pathReplaceY][pathReplaceX];
                 grid[pathReplaceY][pathReplaceX] = ghost;
                 grid[ghostPosY][ghostPosX] = tempTwo;
                 ghostPosY++;
                 x++;
             }
        }    
        
        // This is a timer I am trying to build into the ghost!
        /* 
        if (time % 20 == 0){
            downRigt = 3;
        }
        if (time % 40 == 0){
            downRigt = 0;
        } */                        
       
    
    x = 0; // Reset x to zero 
    
        if(tempRightEnabled == false && grid[ghostPosY][ghostPosX+1] != wall){
            while(x != 2 && grid[ghostPosY][ghostPosX+1] != wall){
                pathReplaceX = pathReplaceX+1;
                tempTwo = grid[pathReplaceY][pathReplaceX];
                grid[pathReplaceY][pathReplaceX] = ghost;
                grid[ghostPosY][ghostPosX] = tempTwo;
                ghostPosX++;              
                x++;
            }
        }

        // This is a timer I am trying to build into the ghost!
        /* if (time % 20 == 0){
            upLeft = -3;
        }
        if (time % 40 == 0){
            upLeft = 0;
        } */ 
              
       else if(tempLeftEnabled == false && grid[ghostPosY][ghostPosX-1] != wall){
            while(x != 1 && grid[ghostPosY][ghostPosX-1] != wall){
                pathReplaceX = pathReplaceX-1;
                tempTwo = grid[pathReplaceY][pathReplaceX];
                grid[pathReplaceY][pathReplaceX] = ghost;
                grid[ghostPosY][ghostPosX] = tempTwo;
                ghostPosX--;
                
            }   
       }
                
       
       //  This is a position checker I am thinking of building into the ghost
       //  so that it does not get suck in corners or get stuck at all 
       
       /*       
       if (temp1 == tempTwo || temp2 == tempTwo){
          bool tempRightEnabled = true;
          bool tempLeftEnabled = false;
          bool tempDownEnabled = true;
          bool tempUpEnabled = false;
       } 
       */


}

/* This is Trino's ghost function.
   The objective of my ghost function is to simply get the ghosts to chase pacman.
   For no other reason did I choose to call my function 'ghostDudeChasing'.
*/
void ghostDudeChasing(int &ghostPosY, int &ghostPosX, int pacManPosY, int pacManPosX, char grid[17][17]){
    
    // The character values are named and given values
    char temp = ' ';
    char wall = 219;
    
    /* 'ghostPosY' is the ghost's vertical value in the grid. 'pacManPosY' is the 
       vertical pacman value in the grid. 
       If pacman's vertical position on the grid has a lower value than the ghost's
       vertical position, and there is no wall to where the ghost will move, 
       this conditional statement will run, making the ghost move an 
       UPWARD direction in the grid.*/
    if((ghostPosY > pacManPosY) && (grid[ghostPosY - 1][ghostPosX] != wall)){
        
		// The character to where the ghost will move ahead to will get passed down to a temporary value
        temp = grid[ghostPosY - 1][ghostPosX];
		
		// The ghost character and the character to where the ghost will move ahead of will be switched
        grid[ghostPosY - 1][ghostPosX] = grid[ghostPosY][ghostPosX];
		
		// The temporary value will get passed to where the the ghost's character used to be at
        grid[ghostPosY][ghostPosX] = temp;
		
		// After all the operations have taken place, the ghost position value will finally decrement
        ghostPosY--;
    }
    /* 'ghostPosY' is the ghost's vertical value in the grid. 'pacManPosY' is the 
       vertical pacman value in the grid. 
       If pacman's vertical position on the grid has a higher value than the ghost's
       vertical position, and there is no wall to where the ghost will move,
       this conditional statement will run, making the ghost move a DOWNWARD
       direction in the grid.*/    
    else if((ghostPosY < pacManPosY) && (grid[ghostPosY + 1][ghostPosX] != wall)){
		
		// The character to where the ghost will move ahead to will get passed down to a temporary value
		temp = grid[ghostPosY + 1][ghostPosX];
        
		// The ghost character and the character to where the ghost will move ahead of will be switched
		grid[ghostPosY + 1][ghostPosX] = grid[ghostPosY][ghostPosX];
		
		// The temporary value will get passed to where the the ghost's character used to be at
        grid[ghostPosY][ghostPosX] = temp;
		
		// After all the operations have taken place, the ghost position value will finally increment
        ghostPosY++;
    }
    /* 'ghostPosX' is the ghost's horizonal value in the grid. 'pacManPosX' is the
       horizontal pacman value in the grid.
       If pacman's horizontal position on the grid has a lower value than the ghost's
       horizontal position, and there is no wall to where the ghost will move,
       this conditional statement will run, making the ghost move LEFT in the grid.*/
    else if((ghostPosX > pacManPosX) && (grid[ghostPosY][ghostPosX - 1] != wall)){
    
		// The character to where the ghost will move ahead to will get passed down to a temporary value
		temp = grid[ghostPosY][ghostPosX - 1];
        
		// The ghost character and the character to where the ghost will move ahead of will be switched
		grid[ghostPosY][ghostPosX - 1] = grid[ghostPosY][ghostPosX];
		
		// The temporary value will get passed to where the the ghost's character used to be at
        grid[ghostPosY][ghostPosX] = temp;
		
		// After all the operations have taken place, the ghost position value will finally decrement
        ghostPosX--;
    }
    /* 'ghostPosX' is the ghost's horizontal value in the grid. 'pacManPosX' is the
       horizontal pacman value in the grid.
       If pacman's horizontal position on the grid has a higher value that the ghost's
       horizontal position, and there is no wall to where the ghost will move,
       this conditional statement will run, making the ghost move RIGHT in the grid.*/
    else if((ghostPosX < pacManPosX) && (grid[ghostPosY][ghostPosX + 1] != wall)){
    
		// The character to where the ghost will move ahead to will get passed down to a temporary value
        temp = grid[ghostPosY][ghostPosX + 1];
        
		// The ghost character and the character to where the ghost will move ahead of will be switched
		grid[ghostPosY][ghostPosX + 1] = grid[ghostPosY][ghostPosX];
        
		// The temporary value will get passed to where the the ghost's character used to be at
		grid[ghostPosY][ghostPosX] = temp;
		
		// After all the operations have taken place, the ghost position value will finally increment
        ghostPosX++;
    }
}/* The end of my ghost chasing pacman function */

//==========================================================================ends

// This function's purpose is to make the color changes in the game
void setColorOnGrid(char grabbedChar, int amountAllowed) {
	// These are the characters that will be detected
	char pacDude = 2;
	char wall = 219;
    char path = 249;
	char ghost = 1;
	char boost = 15;
	char  crystal = 3;
 
    // depending on the character detected
	if(grabbedChar == pacDude) { 
		setcolor(14); 
	}
	if(grabbedChar == wall) {
		setcolor(2);
	} else if(grabbedChar == path) {
		setcolor(14);
	} else if(grabbedChar == ghost) {
		setcolor(12);
	} else if(grabbedChar == boost) {
		 setcolor(14);
	} else if (grabbedChar == crystal) {
		setcolor(7);
	}

}
void boostColor(char grabbedChar, int amountAllowed,bool boostOn) {
	// These are the characters that will be detected
	char pacDude = 2; 
    char ghost = 1;
    char crystal = 3;
    // depending on the character detected
        if(boostOn == true && grabbedChar == pacDude){
                  setcolor(amountAllowed);     
                }
        else if(boostOn == false && grabbedChar == pacDude){        
        setcolor(14);
        }
       if(boostOn == true && grabbedChar == ghost){
        setcolor(11);   
}
if (grabbedChar == crystal ){
setcolor(amountAllowed);
}}



// This function's purpose is to exit the game if the user presses 'ESC' on the
// keyboard while the game runs. 
void toQuitTheGame(bool &toRun){
	string userInput = " ";
	bool repeat = true;
	
	// While the statement remains true, this loop will run.
	while(repeat == true) {
        clearScreen();
        setcolor(15);
		cout << "Are you sure you want to quit the game, y/n?";
		cin >> userInput;
	    
	    // If the user inputs a "y" or a "Y" for yes, this loop will run
		if (userInput == "Y" || userInput == "y") {
            
            // 'toRun' will be turned into false, which will modify the boolean
            // value 'run' in the Game() function
			toRun = false;
			
			// 'repeat' will be false, meaning that the user won't be reasked 
			// for input after this loop taked 
			repeat = false;		
		}
		
		// If the user inputs a "N" or"n" for no, this loop will run
        else if(userInput == "N" || userInput == "n") {
            
            // 'toRun' will be true, which will modify the boolean value
            // 'run' in the Game() function
			toRun = true;
			
			// 'repeat' will be false, meaning that the user won't be reasked 
			// for input after this loop taked place
			repeat =  false;
		}
		
		// else if the user makes incorrect input, the this loop will run
        else {
             
            /* 'repeat' will remain true, which will make the while loop in 
               this program to repeat, meaning that the user will be reasked
               for input */
			repeat = true;
		}
	}
}


/* This function's purpose is to clear out the buffer from user's input, that 
   way if the user make multiple keystrokes on the keyboard while the game plays,
   they get cleared out, that way the pacman makes not extra moves. */ 
void clearBuffer(char &movingDirection){
    
    // The character value will be resetted to an empty value
    movingDirection = ' ';
}


void consoleResize(unsigned int x, unsigned int y) {
	COORD coord;
	//HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

	coord.X = x;
	coord.Y = y;

	SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}

void clearScreen() {
     system("CLS");     
}

void sound(void *P)
{
     //Loop sound
     for(int i = 0; i < 1000; ++i)
      {
             //Slows The pace of the beeps
			 //   Sleep(55);
             {
                        Beep(150,250);Beep(100,500);Beep(150,250);Beep(200,200);Beep(150,500);
                        Sleep(55);
                        Beep(250,250);Beep(200,500);Beep(150,250);Beep(100,200);Beep(150,250);
                        Sleep(55);
             }
      }
      return;
}

//High Scores Function
void HighScores(void){
     
     
     
     //Function variables and constants
     int NumberOfScores = 0;     
     //int Places = 0;
     int myScore = 0;
     int SecondPlace = 0;
     //int i = 0;
     string fileContents = " ";
     string Name = " ";
     

     //Open the input and output files
     ifstream fin("PacmanHighScores.txt");
     ofstream sout ("PacmanHighScores.txt");
      
        
     cout << "please enter score" << endl;
     cin >> myScore; 
     cout << "please enter name" << endl;
     cin>> Name;
     //cin >>NumberOfScores;
     sout << left << setw(10) <<"Place";
     sout<<left << setw(5) <<"Name";        
     sout <<left << setw(20) <<"Scores";        


     sout <<NumberOfScores <<"   " <<endl;                 

     //Extract File contents
     while(fin >> fileContents)
     {
         
        //  cout << fileContents << " " << endl;
          
     //End of loop    
     }
       
     if(myScore > SecondPlace)
     {
           
   /*       cout<<endl<<"Congratulations, You're in the top Two!"<<endl;
     
          cout<< (Places + 1) <<"  " << Name <<"  "<< myScore   <<endl;          
          sout<<"  " <<(Places + 1) <<"      "<< Name <<"          "<< myScore <<"   "<<endl;
          */
     
          Bubblesort(); 
          
     //End of If statement               
     }
     
     //System pause
     system("PAUSE");
     
//End of Function     
}

//Bubblesort Function
void Bubblesort(void){
     
     //Function variables and constants
     const int NumberOfHighScores = 3;
     int x = 0;
     int temp = 0;
     int FirstPlace = 0;
     int SecondPlace = 0;
     int myScore = 0;
     
     //Function Array
     int Scores[]={FirstPlace,SecondPlace,myScore};
     
     FirstPlace = Scores[0];
     SecondPlace = Scores[1];
     
     for(int pass = 1; pass < NumberOfHighScores; pass ++)
           {     
                 x = 0;
                 for(int tests = (NumberOfHighScores - pass); tests > 0; tests--)
                 {
					 if(Scores[x] > Scores[x + 1])
					 {
						temp = Scores[x + 1];
						Scores[x + 1] = Scores[x];
						Scores[x] = temp;

						x++;
					 }
                 } 
           }
     
//End of Bubblesort function     
}

void ghostDeath(int &ghostExterminator, int &ghostTimeOff){

     int m = ghostTimeOff;
     int CountDownTimeForGhostKilling = ghostExterminator;

//     if((m==0)||(

        // This conditionals tells' the user how much time pacman has to exterminate
        // the ghosts.
        if(m  <= 18){
        --CountDownTimeForGhostKilling;
        cout << endl << "KILL THE GHOST " << CountDownTimeForGhostKilling;
             if(CountDownTimeForGhostKilling == 0){
             CountDownTimeForGhostKilling = 18;
             }
        }

        else if((19<m)&&(m<30)){
             cout << endl <<"The Ghost Have Gain Their Power" << endl;
             }

            ghostTimeOff = m;
            ghostExterminator = CountDownTimeForGhostKilling;

}

// This is the timer protype
void clickTime(int &time, int &loops){


     int loopRepeats = loops;
     int clockTicker = time;
     int clockReset = 20;

     // This tells the program after the loop repeats 7 times, to decrement a second!
     if(loopRepeats==1){
        clockTicker--;
        loopRepeats = 0;
        }
     
     if(clockTicker==-1){
     cout << endl <<"Your Time is UP!!!" << endl;

     youAreSoDead(false);
     clockTicker = clockReset;
     }
     else{
    // youAreSoDead(true);
     }
     time = clockTicker;
     loops = loopRepeats;
}


//This will Be My GAMEOVER TRIGGER That will decide your death!
//Under Cunstruction by Israel Estrada JR!!!
void youAreSoDead(bool Death){

     // The lifes for pacman should be determine in class, but right now I am
     // assuming we want three lives for pac-man.
     //int iDontKnow = 3;
          
     //While this loop does not equal false, death will not be near
     // for pac-man. But if the statement is false one life will
     // decrement.
     if(Death == false){
              //lifeDecrementation(*, Death);
              system("PAUSE");
              }
     
}

// this will be called by the user.
void lifeDecrementation(int &numberOfLives, bool Death){
     //if(Death==false){
     numberOfLives--;

                     // This will execute, if pacman has no lives left!
                     if(numberOfLives==-1){
                     //gameOverLink();//This where I will link GAMEOVERS,
                          // call tyler's game menu, Nohemi's score function,
                          // conncect trino's escape function display GAME OVER 
                     // I should reset the lives back to three here, after
                     // I have the lives working properly
                                   }
                     //}
                                   
}

//this will be called by the program.
//This will display how many lives pacman has.
// I will write this in wiki, and explain to the people how to call this function.
void displayOfTheLivesPacmanHasLeft(int numberOfLives){
     char pacMan = 2;//move this to the main game function
     cout << "Lives Left: ";
     for(int x = numberOfLives; x>0;x--){
             cout << pacMan;
             }
     
}

void gameOverLink(){
     void toQuitTheGame();
     
                    //gameOverLink();//This where I will link GAMEOVERS,
                    // call tyler's game menu, Nohemi's score function,
                    // conncect trino's escape function display GAME OVER 

}

int getOption(){
    int number_Entered = 0;
    
    cout << "Please enter one of the following numbers. \n";
    
    cout << left << setw(4) << " (1) " << left << setw(20) 
         << "PLAY GAME" << endl;
    cout << left << setw(4) << " (2) " << left << setw(20) << "QUIT" << endl;   
    cout << endl << right << setw(4) << "> ";
      
    cin >> number_Entered;
    return number_Entered;
    }

